package com.hema.auction.fragment;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hema.auction.R;
import com.hema.auction.activity.GoodsDetailsActivity;
import com.hema.auction.activity.H5Activity;
import com.hema.auction.activity.RechargeActivity;
import com.hema.auction.activity.SunSquareActivity;
import com.hema.auction.activity.TenZoneActivity;
import com.hema.auction.adapter.FragAdapter;
import com.hema.auction.base.BaseFragment;
import com.hema.auction.bean.SysUnits;
import com.hema.auction.event.NoticeDataEvent;
import com.hema.auction.http.HttpTag;
import com.hema.auction.http.UrlManager;
import com.hema.auction.http.biz.HttpManager;
import com.hema.auction.listener.OnScrollChangeListener;
import com.hema.auction.utils.Constant;
import com.hema.auction.utils.GlideUtils;
import com.hema.auction.utils.Utils;
import com.hema.auction.widget.view.PagerScrollView;
import com.hema.auction.widget.view.TitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.bgabanner.BGABanner;
import ezy.ui.view.NoticeView;
import okhttp3.Call;

/**
 * 描述:
 * 作者:john
 */
public class IndexFragment extends BaseFragment {


    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(R.id.banner)
    BGABanner banner;
    @BindView(R.id.notice_view)
    NoticeView noticeView;
    @BindView(R.id.ll_notice)
    LinearLayout llNotice;
    @BindView(R.id.tablayout)
    TabLayout tablayout;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.app_bar)
    LinearLayout appBar;
    @BindView(R.id.coordinator_layout)
    LinearLayout coordinatorLayout;
    @BindView(R.id.scrollView)
    PagerScrollView scrollView;
    @BindView(R.id.notice_view_float)
    NoticeView noticeViewFloat;
    @BindView(R.id.ll_float_notice)
    LinearLayout llFloatNotice;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;

    private int floatNoticeY;
    private String[] title = new String[]{"正在热拍", "我在拍", "我的收藏"};
    private List<Fragment> fragments = new ArrayList<>();
    private List<SysUnits> sysUnitses;

    @Override
    protected int getLayout() {
        return R.layout.fragment_index;
    }

    @Override
    protected void init() {
        super.init();
        EventBus.getDefault().register(this);
        titleView.setNewMessageBg(R.drawable.bg_read_status_white);
        banner.setFocusable(true);
        banner.setFocusableInTouchMode(true);
        banner.requestFocus();
        banner.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, Utils.getDeviceWidth(getActivity()) * 4 / 9));
        banner.setAdapter((banner1, view, model, position) -> {
            ImageView iv = (ImageView) view;
            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
            GlideUtils.load(getActivity(), (String) model, iv);
        });
        banner.setDelegate(new BGABanner.Delegate() {
            @Override
            public void onBannerItemClick(BGABanner banner, View itemView, Object model, int position) {
                SysUnits item = sysUnitses.get(position);
                switch (item.getUrlType()) {//1跳H5，2跳详情，3跳充值
                    case 1:
                        Bundle bundle = new Bundle();
                        bundle.putString(Constant.EXTRA_URL, item.getUrl());
                        intentTo(H5Activity.class, bundle);
                        break;
                    case 2:
                        bundle = new Bundle();
                        bundle.putString(Constant.EXTRA_GOOD_ID, item.getUrl());
                        intentTo(GoodsDetailsActivity.class, bundle);
                        break;
                    case 3:
                        intentTo(RechargeActivity.class);
                        break;
                    default:
//                        bundle = new Bundle();
//                        bundle.putString(Constant.EXTRA_GOOD_ID, "101");
//                        intentTo(GoodsDetailsActivity.class, bundle);
                        break;
                }
            }
        });
        refreshLayout.setColorSchemeResources(R.color.colorPrimary);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                IndextabFragment fragment = (IndextabFragment) fragments.get(tablayout.getSelectedTabPosition());
                fragment.refresh();
                getData();
            }
        });
        fragments.add(IndextabFragment.newInstance(0));
        fragments.add(IndextabFragment.newInstance(1));
        fragments.add(IndextabFragment.newInstance(2));
        scrollView.setFragments(fragments);
        scrollView.setTabIndex(0);
        for (Fragment fragment : fragments) {
            IndextabFragment indextabFragment = (IndextabFragment) fragment;
            indextabFragment.refreshLayout(refreshLayout);
        }
        FragAdapter adapter = new FragAdapter(getChildFragmentManager(), fragments, title);
        viewPager.setAdapter(adapter);
        tablayout.setupWithViewPager(viewPager);
        viewPager.setOffscreenPageLimit(2);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (!isLogin && position > 0) {
                    goLogin();
                    viewPager.setCurrentItem(0);
                } else {
                    scrollView.setTabIndex(position);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        llNotice.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        int[] location = new int[2];
                        llNotice.getLocationOnScreen(location);
                        floatNoticeY = location[1] - titleView.getHeight() - Utils.getStatusBarHeight(getActivity());
                        llNotice.getViewTreeObserver()
                                .removeGlobalOnLayoutListener(this);
                        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (getView().getBottom() - llFloatNotice.getBottom() - llFloatNotice.getHeight())-Utils.dp2px(getActivity(),10));
                        viewPager.setLayoutParams(lp);
                        llFloatNotice.setVisibility(View.GONE);
                    }
                });
        scrollView.setListener(new OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY >= floatNoticeY) {
                    llFloatNotice.setVisibility(View.VISIBLE);
                } else {
                    llFloatNotice.setVisibility(View.GONE);
                }
            }
        });
        refreshLayout.setRefreshing(true);
        getData();
    }


    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onNoticeDataEvent(NoticeDataEvent event) {
        noticeView.start(event.getNotices());
        noticeViewFloat.start(event.getNotices());
    }

    /**
     * 获取首页banner广告和最新成交商品
     */
    private void getData() {
        SysUnits info = (SysUnits) aCache.getAsObject(Constant.CACHE_INDEX_BANNER);
        if (info != null)
            HttpManager.getInstance(getActivity()).getBanner(info.getValue(), IndexFragment.this);
    }

    @OnClick({R.id.tv_recharge, R.id.tv_ten_zone, R.id.tv_sun, R.id.tv_helper})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_recharge:
                //充值
                intentTo(RechargeActivity.class);
                break;
            case R.id.tv_ten_zone:
                //十元专区
                intentTo(TenZoneActivity.class);
                break;
            case R.id.tv_sun:
                intentTo(SunSquareActivity.class);
                break;
            case R.id.tv_helper:
                Bundle bundle = new Bundle();
                bundle.putString(Constant.EXTRA_TITLE, ((TextView) v).getText().toString());
                bundle.putString(Constant.EXTRA_URL, UrlManager.H5_HELP);
                intentTo(H5Activity.class, bundle);
                break;


        }
    }

    @Override
    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {
        super.onSuccess(httpTag, call, result);
        switch (httpTag) {
            case TAG_GET_BANNER:
                try {
                    if (result.getInt("errcode") == 0) {
                        sysUnitses = new Gson().fromJson(result.getJSONArray("data").toString(), new TypeToken<List<SysUnits>>() {
                        }.getType());
                        List<String> imgs = new ArrayList<>();
                        for (SysUnits sysUnits : sysUnitses) {
                            imgs.add(sysUnits.getImg());
                        }
                        banner.setAutoPlayAble(imgs.size() > 1);
                        banner.setData(imgs, null);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
//            case TAG_GET_NEWST_ORDERS:
//                try {
//                    if (result.getInt("errcode") == 0) {
//                        List<GoodsInfo> goodsInfos = new Gson().fromJson(result.getJSONArray("data").toString(), new TypeToken<List<GoodsInfo>>() {
//                        }.getType());
//                        setNewestOrdersData(goodsInfos);
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
